<template>
  <el-card class="app-container">
    <c-u-r-d-table :option="option" ref="table"/>

    <dialog-columns-form
      v-model="formData"
      width="900px"
      title="跟进"
      :visible.sync="followDialogShowed"
      :columns="followColumns"
      @submit="handleSubmitFollowCmd"
    />
    <dialog-columns-form
      v-model="formData"
      width="900px"
      title="提交"
      :visible.sync="submitDialogShowed"
      :columns="submitColumns"
      @submit="handleDoSubmitFollow"
    />
    <dialog-columns-form
      v-model="formData"
      width="1100px"
      :title="isCheckPassed?'审核通过':'审核驳回'"
      :visible.sync="authDialogShowed"
      :columns="authColumns"
      @submit="handleSubmitAuth"
    />

    <el-dialog
      :visible.sync="importDialogShowed"
      title="批量导入"
      width="700px"
      :close-on-click-modal="false"
      center
      top="30vh"
    >
      <el-alert type="warning" :closable="false" show-icon style="line-height: 1.6">
        单次最多可导入的数据数量最多10000条。若数量较多，可拆分文件后上传
      </el-alert>
      <div slot="footer" class="flex">
        <div class="flex-con" style="text-align: left;font-size: 14px">
          <a href="/template/发货投诉导入模板.xlsx" target="_blank">
            下载导入模板
          </a>
        </div>
        <file-uploader
          title="上传导入文件"
          icon=""
          size="mini"
          type="primary"
          action="/api/cmt/delivery-complain/import"
          @success="handleImportSuccess"
        />
        <div class="flex-con"></div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="importOrderAmountDialogShowed"
      title="导入订单金额"
      width="700px"
      :close-on-click-modal="false"
      center
      top="30vh"
    >
      <el-alert type="warning" :closable="false" show-icon style="line-height: 1.6">
        单次最多可导入的数据数量最多10000条。若数量较多，可拆分文件后上传
      </el-alert>
      <div slot="footer" class="flex">
        <div class="flex-con" style="text-align: left;font-size: 14px">
          <a href="/template/发货订单金额导入模板.xlsx" target="_blank">
            下载导入模板
          </a>
        </div>
        <file-uploader
          title="上传导入文件"
          icon=""
          size="mini"
          type="primary"
          action="/api/cmt/delivery-complain/import-order-amount"
          @success="handleImportOrderAmountSuccess"
        />
        <div class="flex-con"></div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="removeCondShowed"
      title="批量清理"
      width="500px"
      :close-on-click-modal="false"
      center
      top="30vh"
    >
      <el-form ref="form" :model="removeCondForm" :rules="removeCondRule" label-width="80px">
        <el-form-item prop="payOutType" label="赔付类型">
          <el-select v-model="removeCondForm.payOutType" clearable filterable size="mini">
            <el-option
              v-for="op in payOutTypeOptions"
              :key="op.value"
              :value="op.value"
              :label="op.label"
            />

          </el-select>
        </el-form-item>
        <el-form-item prop="gmtCreate" label="导入日期">
          <el-date-picker
            v-model="removeCondForm.gmtCreate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            size="mini"
            end-placeholder="结束日期"
            align="right"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :picker-options="{
              ...dateRangePickerOptions,
              disabledDate: (time) => {
                return time.getTime() > Date.now()
              }
            }"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="removeCondShowed = false">取消</el-button>
        <el-button size="mini" type="primary" :loading="isRemovingCond" @click="handleRemoveCond">确定</el-button>
      </div>
    </el-dialog>

  </el-card>
</template>

<script>

import ColumnType from '@/framework/constant/ColumnType'
import { deliveryComplainApi } from '@/feature/cmt/infra/api/deliveryComplainApi'
import CURDTable from '@/framework/components/table/CURDTable'
import { storeApi } from '@/feature/mct/infra/api/storeApi'
import { adminApi } from '@/feature/mgr/infra/api/adminApi'
import ComplainReasonEnum from '@/feature/cmt/infra/constants/ComplainReasonEnum'
import ComplainFinalStatusEnum from '@/feature/cmt/infra/constants/ComplainFinalStatusEnum'
import DeliveryComplainStatusEnum from '@/feature/cmt/infra/constants/DeliveryComplainStatusEnum'
import CheckStatusEnum from '@/infra/constant/CheckStatusEnum'
import DateUtil from '@/framework/infra/util/DateUtil'
import DialogColumnsForm from '@/framework/components/form/DialogColumnsForm'
import YesNoEnum from '@/infra/constant/YesNoEnum'
import { mapGetters } from 'vuex'
import FileUploader from '@/framework/components/FileUploader'
import AdminTypeEnum from '@/feature/mgr/infra/constants/AdminTypeEnum'
import PayOutTypeEnum from '@/feature/cmt/infra/constants/PayOutTypeEnum'
import DateType from '@/framework/constant/DateType'
import FormRuleValidator from '@/framework/infra/validator/FormRuleValidator'
import { dateRangePickerOptions } from '@/framework/constant/DatePickerOptions'
import { clickFarmApi } from '@/feature/cmt/infra/api/clickFarmApi'

export default {
  components: { DialogColumnsForm, CURDTable, FileUploader },
  computed: {
    ...mapGetters(['userInfo']),
    status() {
      return this.$route.meta.status || null
    },
    option() {
      let list = 'list'
      let disableDefaultSearchParam = false
      if (this.status === DeliveryComplainStatusEnum.WAIT_FOLLOW.id) {
        disableDefaultSearchParam = true
        list = 'listCanFollow'
      } else if (this.status === DeliveryComplainStatusEnum.ING.id) {
        list = 'listMyFollow'
        disableDefaultSearchParam = true
      } else if (this.status === DeliveryComplainStatusEnum.WAIT_FINISH.id) {
        list = 'listCanCheck'
        disableDefaultSearchParam = true
      }
      return {
        showSelection: this.mineCheckFlag === 0 && this.status !== null,
        disableDefaultSearchParam,
        requestApi: deliveryComplainApi,
        initListParams: () => {
          if (this.status === DeliveryComplainStatusEnum.WAIT_FINISH.id && !this.mineCheckFlag) {
            return {
              status: this.status
            }
          }
          return {}
        },
        requestApiNames: {
          list
        },
        tab: this.status === DeliveryComplainStatusEnum.WAIT_FINISH.id ? {
          options: [{
            value: 0,
            text: '待审核'
          }, {
            value: 1,
            text: '已审核'
          }],
          defaultValue: 0,
          onChange: (v) => {
            this.mineCheckFlag = v
            this.$refs.table.setListParam('mineCheckFlag', v).reloadTable()
          }
        } : null,
        groupId: this.mineCheckFlag,
        columns: [
          {
            label: '店铺',
            prop: 'storeId',
            searchable: true,
            width: 120,
            type: ColumnType.SELECT,
            required: true,
            options: storeApi.options()
          },
          // {
          //   label: '投诉申请时间',
          //   required: false,
          //   prop: 'complainDate',
          //   sortable: 'custom',
          //   width: 120,
          //   type: ColumnType.DATE,
          //   searchable: true
          // },
          {
            label: '投诉订单编号',
            required: true,
            searchable: true,
            width: 150,
            prop: 'complainNo',
            rules: [
              { validator: FormRuleValidator.validateNumLen(19, '投诉订单编号必须是19位数字'), trigger: 'blur' }
            ]
          },
          {
            label: '投诉撤销人',
            // required: true,
            searchable: true,
            type: ColumnType.SELECT,
            width: 150,
            options: adminApi.listAllOfType(AdminTypeEnum.SELLER_AFTER.id),
            prop: 'reBackManId'
          },
          // {
          //   label: '订单编号',
          //   required: true,
          //   width: 100,
          //   prop: 'orderNo'
          // },
          // ,
          // {
          //   label: '跟进截止倒计时',
          //   width: 120,
          //   // hiddenInForm: true,
          //   color: '#f56c6c',
          //   required: true,
          //   prop: 'followEndLeftSeconds',
          //   type: ColumnType.LEFT_TIME_COUNT
          // },
          {
            label: '订单金额',
            width: 100,
            type: ColumnType.NUMBER,
            required: true,
            onChange: ({ formData }) => {
              if (formData.complainReason === '') {
                return
              }
              const option = ComplainReasonEnum.getById(formData.complainReason)
              if (option && formData.orderAmount) {
                if (option.percent) {
                  formData.payOutAmount = (formData.orderAmount * option.percent).toFixed(2)
                } else {
                  formData.payOutAmount = 0
                }
              } else {
                formData.payOutAmount = 0
              }
            },
            prop: 'orderAmount'
          },

          // {
          //   label: '千牛旺旺号',
          //   width: 100,
          //   required: true,
          //   prop: 'wanWanNo'
          // },
          {
            label: '赔付原因',
            prop: 'complainReason',
            onChange: ({ value, formData }) => {
              const option = ComplainReasonEnum.getById(value)
              if (option && formData.orderAmount) {
                if (option.percent) {
                  formData.payOutAmount = (formData.orderAmount * option.percent).toFixed(2)
                } else {
                  formData.payOutAmount = 0
                }
              } else {
                formData.payOutAmount = 0
              }
            },
            width: 220,
            required: true,
            searchable: true,
            options: ComplainReasonEnum,
            type: ColumnType.SELECT
          },
          {
            label: '赔付类型',
            prop: 'payOutType',
            width: 120,
            required: true,
            formCached: true,
            searchCached: true,
            // defaultValue: PayOutTypeEnum.BACK.id,
            searchable: true,
            options: PayOutTypeEnum,
            type: ColumnType.SELECT
          },
          {
            searchable: true,
            label: '赔付时间',
            type: ColumnType.DATETIME,
            searchOption: {
              options: {
                type: DateType.DATERANGE
              }
            },
            // hiddenInForm: true,
            prop: 'payOutTime'
          },
          {
            label: '本应赔付金额',
            width: 120,
            renderOptions: {
              precision: 2
            },
            type: ColumnType.NUMBER,
            prop: 'payOutAmount'
          },
          {
            label: '撤销赔付金额',
            width: 120,
            // hiddenInForm: true,
            type: ColumnType.NUMBER,
            prop: 'backOutAmount'
          },
          // {
          //   label: '最终处理结果',
          //   width: 120,
          //   prop: 'finalStatus',
          //   // required: true,
          //   // hiddenInForm: true,
          //   options: ComplainFinalStatusEnum,
          //   type: ColumnType.SELECT
          // },
          // {
          //   label: '投诉链接',
          //   width: 120,
          //   span: 24,
          //   type: ColumnType.TEXTAREA,
          //   prop: 'tbLink',
          //   required: true
          // },
          // {
          //   label: '投诉是否完结',
          //   prop: 'finishFlag',
          //   required: true,
          //   defaultValue: 0,
          //   searchable: true,
          //   width: 100,
          //   type: ColumnType.RADIO,
          //   options: YesNoEnum
          // },
          {
            label: '备注',
            width: 200,
            span: 24,
            type: ColumnType.TEXTAREA,
            prop: 'remark'
          },
          // {
          //   label: '跟进记录',
          //   prop: 'followRecord',
          //   span: 24,
          //   width: 100,
          //   viewDetail: true,
          //   hiddenInForm: true,
          //   type: ColumnType.TEXTAREA
          // },
          {
            label: '投诉处理人',
            prop: 'handlerId',
            width: 100,
            searchable: true,
            hiddenInForm: true,
            options: adminApi.listAll(),
            type: ColumnType.SELECT
          }, {
            label: '状态',
            prop: 'status',
            width: 100,
            searchable: true,
            hiddenInForm: true,
            options: DeliveryComplainStatusEnum,
            type: ColumnType.SELECT
          },
          {
            label: '跟进人',
            width: 100,
            searchable: true,
            hiddenInForm: true,
            prop: 'followerId',
            type: ColumnType.SELECT,
            options: adminApi.listAll()
          },
          {
            label: '审核状态',
            width: 100,
            searchable: true,
            hiddenInForm: true,
            type: ColumnType.RADIO,
            options: CheckStatusEnum,
            prop: 'checkStatus'
          },
          {
            label: '审核人',
            width: 100,
            searchable: true,
            hiddenInForm: true,
            prop: 'checkerId',
            type: ColumnType.SELECT,
            options: adminApi.listAll()
          },
          {
            label: '审核备注',
            minWidth: 200,
            width: 'auto',
            hiddenInForm: true,
            prop: 'checkResult'
          },
          {
            label: '投诉处罚凭证',
            width: 100,
            hiddenInForm: true,
            type: ColumnType.IMAGE,
            prop: 'checkRemarkPic'
          },
          {
            label: '创建时间',
            type: ColumnType.DATETIME,
            hiddenInForm: true,
            prop: 'gmtCreate'
          },
          {
            label: '修改时间',
            type: ColumnType.DATETIME,
            hiddenInForm: true,
            prop: 'gmtModified'
          }
        ]
      }
    }
  },
  data() {
    return {
      removeCondShowed: false,
      isRemovingCond: false,
      dateRangePickerOptions,
      removeCondForm: {
        gmtCreate: []
      },
      payOutTypeOptions: PayOutTypeEnum.getOptions(),
      removeCondRule: {
        gmtCreate: [
          {
            required: true,
            message: '请选择导入日期',
            trigger: 'blur'
          }
        ],
        payOutType: [
          {
            required: true,
            message: '请选择赔付类型',
            trigger: 'blur'
          }
        ]
      },
      importDialogShowed: false,
      importOrderAmountDialogShowed: false,
      isCheckPassed: true,
      formData: {},
      submitDialogShowed: false,
      mineCheckFlag: 0,
      followDialogShowed: false,
      authDialogShowed: false,
      authColumns: [
        {
          label: '店铺',
          span: 6,
          prop: 'storeId',
          searchable: true,
          width: 120,
          type: ColumnType.PLAIN_TEXT,
          options: storeApi.options()
        },
        {
          label: '投诉申请时间',
          span: 6,
          prop: 'complainDate',
          width: 120,

          type: ColumnType.PLAIN_TEXT,
          searchable: true
        },
        {
          label: '投诉编号',
          span: 6,
          type: ColumnType.PLAIN_TEXT,
          width: 100,
          prop: 'complainNo'
        },
        {
          label: '订单金额',
          width: 100,
          span: 6,
          type: ColumnType.PLAIN_TEXT,
          prop: 'orderAmount'
        },
        {
          label: '千牛旺旺号',
          width: 100,
          span: 6,
          type: ColumnType.PLAIN_TEXT,
          prop: 'wanWanNo'
        },
        {
          label: '赔付原因',
          prop: 'complainReason',
          searchable: true,
          span: 6,
          options: ComplainReasonEnum,
          type: ColumnType.PLAIN_TEXT
        },
        {
          label: '本应赔付金额',
          width: 120,
          type: ColumnType.PLAIN_TEXT,
          renderOptions: {
            precision: 2
          },
          span: 6,
          prop: 'payOutAmount'
        },
        {
          label: '撤销赔付金额',
          width: 120,
          type: ColumnType.PLAIN_TEXT,
          span: 6,
          hiddenInForm: true,
          prop: 'backOutAmount'
        },
        {
          label: '最终处理结果',
          width: 120,
          prop: 'finalStatus',
          span: 6,
          required: true,
          hiddenInForm: true,
          options: ComplainFinalStatusEnum,
          type: ColumnType.PLAIN_TEXT
        },
        // {
        //   label: '投诉链接',
        //   width: 120,
        //   span: 6,
        //   viewAsLink: true,
        //   type: ColumnType.PLAIN_TEXT,
        //   prop: 'tbLink'
        // },
        {
          span: 6,
          label: '跟进记录',
          prop: 'followRecord',
          type: ColumnType.PLAIN_TEXT,
          width: 100,
          viewDetail: true,
          hiddenInForm: true
        },
        {
          label: '投诉处理人',
          prop: 'handlerId',
          width: 100,
          span: 6,
          searchable: true,
          hiddenInForm: true,
          type: ColumnType.PLAIN_TEXT,
          options: adminApi.listAll()
        }, {
          label: '状态',
          prop: 'status',
          span: 6,
          width: 100,
          searchable: true,
          hiddenInForm: true,
          options: DeliveryComplainStatusEnum,
          type: ColumnType.PLAIN_TEXT
        },
        {
          label: '跟进人',
          width: 100,
          searchable: true,
          hiddenInForm: true,
          span: 6,
          prop: 'followerId',
          type: ColumnType.PLAIN_TEXT,
          options: adminApi.listAll()
        },
        {
          label: '备注',
          width: 150,
          span: 24,
          type: ColumnType.PLAIN_TEXT,
          prop: 'remark'
        },
        {
          label: '投诉处罚凭证',
          width: 120,
          showFilter: () => this.isCheckPassed,
          type: ColumnType.IMAGE,
          prop: 'remarkPic'
        },
        {
          label: '审核备注',
          width: 120,
          span: 24,
          type: ColumnType.TEXTAREA,
          prop: 'checkRemark'
        }
      ],
      submitColumns: [
        {
          label: '备注',
          width: 150,
          span: 24,
          type: ColumnType.TEXTAREA,
          prop: 'remark'
        }
      ],
      followColumns: [
        {
          label: '撤销赔付金额',
          width: 100,
          required: true,
          type: ColumnType.MONEY,
          prop: 'backOutAmount'
        },
        {
          label: '最终处理结果',
          prop: 'finalStatus',
          required: true,
          searchable: true,
          width: 100,
          options: ComplainFinalStatusEnum,
          type: ColumnType.SELECT
        },
        // {
        //   label: '撤销处理人',
        //   prop: 'finisherId',
        //   width: 100,
        //   // required: true,
        //   searchable: true,
        //   options: adminApi.listAllOfType(AdminTypeEnum.BAD_COMMENT_HANDLER.id),
        //   type: ColumnType.SELECT
        // },
        {
          label: '投诉是否完结',
          prop: 'finishFlag',
          required: true,
          searchable: true,
          width: 100,
          type: ColumnType.RADIO,
          options: YesNoEnum
        },
        {
          label: '跟进记录',
          prop: 'followRecord',
          width: 200,
          span: 24,
          rows: 10,
          type: ColumnType.TEXTAREA
        }
      ]
    }
  },
  methods: {
    handleClearAll() {
      this.removeCondForm.gmtCreate = []
      this.removeCondShowed = true
      // this.$refs.table.clearSelection()
    },
    handleCheckResolve({ arg }) {
      this.formData = { ...arg }
      this.formData.remark = ''
      this.formData.checkStatus = 5
      this.isCheckPassed = true
      this.authDialogShowed = true
    },
    handleImport() {
      this.importDialogShowed = true
    },
    handleImportOrderAmount() {
      this.importOrderAmountDialogShowed = true
    },
    handleImportOrderAmountSuccess() {
      this.importOrderAmountDialogShowed = false
      this.$refs.table.reloadTable()
    },
    handleImportSuccess() {
      this.importDialogShowed = false
      this.$refs.table.reloadTable()
    },
    handleCheckReject({ arg }) {
      this.formData = { ...arg }
      this.formData.remark = ''
      this.isCheckPassed = false
      this.formData.checkStatus = 10
      this.authDialogShowed = true
    },
    handleRemoveCond() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isRemovingCond = true
          deliveryComplainApi.removeByCondition(this.removeCondForm).then(() => {
            this.isRemovingCond = false
            this.removeCondShowed = false
            this.$refs.table.reloadTable()
          }).catch(() => {
            this.isRemovingCond = false
          })
        }
      })
    },
    async handleSubmitFollowCmd({ done }) {
      try {
        await deliveryComplainApi.follow(this.formData)
        this.$refs.table.reloadTable()
        this.followDialogShowed = false
      } finally {
        done()
      }
    },
    async handleDoSubmitFollow({ done }) {
      try {
        await deliveryComplainApi.submit(this.formData)
        this.$refs.table.reloadTable()
        this.submitDialogShowed = false
      } finally {
        done()
      }
    },
    handleSubmitFollow({ $service, arg }) {
      this.formData = { ...arg }
      this.submitDialogShowed = true
    },
    async handleRejectFollow({ arg }) {
      const { value } = await this.$prompt('确认拒绝跟进所选记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '拒绝理由不能为空'
      })
      await deliveryComplainApi.followReject({ id: arg.id, remark: value })
      this.$refs.table.reloadTable()
      this.$success('操作成功')
      // this.authDialogShowed = true
    },
    handleFollow({ arg }) {
      this.followDialogShowed = true
      const currentTime = DateUtil.currentTime()
      this.formData = {
        ...arg,
        followRecord: (arg.followRecord ? arg.followRecord + '\n' : '') + `【${this.userInfo.title} ${currentTime}】`
      }
    },
    async handleSubmitAuth({ done }) {
      try {
        await deliveryComplainApi.check({
          ...this.formData,
          checkRemark: this.formData.remark && this.formData.remark.trim() || '',
          idList: [this.formData.id]
        })
        this.$refs.table.reloadTable()
        this.$success('操作成功')
        this.authDialogShowed = false
      } finally {
        done()
      }
    }
  }
}
</script>

